package com.hexinfo.dmpro.common.controller;

import com.hexinfo.dmpro.common.annotation.Log;
import com.hexinfo.dmpro.common.base.BaseRequest;
import com.hexinfo.dmpro.common.base.BaseView;
import com.hexinfo.dmpro.common.base.Page;
import com.hexinfo.dmpro.common.service.LogService;
import com.hexinfo.dmpro.common.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName LogController
 * @Describe
 * @Author ml.wang
 * @Date 2021-06-16
 */
@Api(tags = "系统：日志管理")
@RestController
@RequestMapping("/api/logs")
public class LogController {

    @Autowired
    private LogService logService;

    @Log("INFO日志查询")
    @GetMapping
    public ResponseEntity<Object> queryInfoLogs(BaseView baseView, Page page) {
        return new ResponseEntity<>(logService.queryInfoLogs(BaseRequest.viewToRequest(baseView), page), HttpStatus.OK);
    }

    @Log("用户日志查询")
    @GetMapping("/user")
    public ResponseEntity<Object> queryLogsByUsername(BaseView baseView, Page page) {
        baseView.setCreateBy(SecurityUtils.getUsername());
        return new ResponseEntity<>(logService.queryLogsByUsername(BaseRequest.viewToRequest(baseView), page), HttpStatus.OK);
    }

    @Log("ERROR日志查询")
    @GetMapping("/error")
    public ResponseEntity<Object> queryErrorLogs(BaseView baseView, Page page) {
        return new ResponseEntity<>(logService.queryErrorLogs(BaseRequest.viewToRequest(baseView), page), HttpStatus.OK);
    }

    @Log("删除所有INFO日志")
    @ApiOperation("删除所有INFO日志")
    @DeleteMapping(value = "/del/info")
    public ResponseEntity<Object> delAllInfoLogs(){
        logService.delAllInfoLogs();
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("删除所有ERROR日志")
    @ApiOperation("删除所有ERROR日志")
    @DeleteMapping(value = "/del/error")
    public ResponseEntity<Object> delAllErrorLogs(){
        logService.delAllErrorLogs();
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("导出INFO日志")
    @ApiOperation("导出INFO日志")
    @GetMapping(value = "/download")
    public void download(HttpServletResponse response, BaseView baseView) throws IOException {
        logService.download(logService.queryAllInfoLogs(BaseRequest.viewToRequest(baseView)), response);
    }

    @Log("导出错误日志")
    @ApiOperation("导出错误日志")
    @GetMapping(value = "/error/download")
    public void errorDownload(HttpServletResponse response, BaseView baseView) throws IOException {
        logService.download(logService.queryAllErrorLogs(BaseRequest.viewToRequest(baseView)), response);
    }

}
